package com.atguigu.controller;

import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;
import com.atguigu.utils.MD5Util;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;

@WebServlet("/user/password")
public class UserPasswordController extends HttpServlet {
    //读取用户提交的更改密码数据

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String password = req.getParameter("user_name");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("Session_User");
//        Cookie[] cookies = req.getCookies();
//        String username = cookies[0].getValue();
        //如果输入的原密码和用户保存的密码一致
        if (MD5Util.encrypt(password).equals(user.getPassword())) {
            UserService userService = new UserServiceImpl();
            int rows = userService.updatePassword(MD5Util.encrypt(password), user.getUsername());
            if (rows == 0) {
                System.out.println("更改密码失败");
            } else {
                System.out.println("更改密码成功");
                resp.sendRedirect("/login.html");
            }
        }else {
            resp.sendRedirect("/updatePasswordError.html");
        }
    }
}
